package com.crm.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import cn.hutool.core.date.LocalDateTimeUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.crm.dto.LoginDto;
import com.crm.dto.UserDto;
import com.crm.entity.User;
import com.crm.exception.BaseException;
import com.crm.mapper.UserMapper;
import com.crm.result.PageResult;
import com.crm.service.UserService;
import com.crm.vo.SysUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Service
@Slf4j
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    /**验证码 redis key */
    public static final String CAPTCHA_CODE_KEY = "captcha_codes:";
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public User login(LoginDto loginDto) {
        //校验验证码
        validateCaptcha(loginDto.getCode(), loginDto.getUuid());
        User user = userMapper.selectOne(Wrappers.<User>lambdaQuery().eq(User::getUserName, loginDto.getUsername()));
        if (user == null){
            throw new BaseException("用户不存在");
        }
        if (!user.getPassword().equals(loginDto.getPassword())){
            throw new BaseException("密码错误");
        }
        return user;
    }

    /**
     * 校验验证码
     * @param code
     * @param uuid
     */
    public void validateCaptcha(String code, String uuid){
        String realCode = (String) redisTemplate.opsForValue().get(CAPTCHA_CODE_KEY + uuid);
        if(StringUtils.isEmpty(code)){
            throw new BaseException("验证码错误");
        }
        if (!realCode.equals(code)){
            throw new BaseException("验证码错误");
        }
    }

    @Override
    public SysUser getUser() {
        User user = userMapper.selectOne(Wrappers.<User>lambdaQuery().eq(User::getUserName, "admin"));
        SysUser sysUser = new SysUser();
        return sysUser;
    }

    @Override
    public Set<String> getRoles(SysUser user) {
        Set<String> roles = new HashSet<String>();
        // 管理员拥有所有权限
        roles.add("admin");

        return roles;
    }

    @Override
    public Set<String> getMenuPermission(SysUser user) {
        Set<String> perms = new HashSet<String>();
        // 管理员拥有所有权限
        perms.add("*:*:*");

        return perms;
    }
    /**
     * 判断部门是否存在用户
     *
     * @param deptId 部门ID
     * @return 结果
     */
    @Override
    public boolean hasUserRel(Integer deptId) {
        return userMapper.exists(new LambdaQueryWrapper<User>().eq(User::getDeptId, deptId));
    }


    @Override
    public PageResult list(UserDto userDto) {
        Page<User> page = new Page<>(userDto.getPageNum(), userDto.getPageSize());
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StringUtils.isNotEmpty(userDto.getUserName()), User::getUserName, userDto.getUserName());
        wrapper.like(StringUtils.isNotEmpty(userDto.getPhoneNumber()), User::getPhoneNumber,userDto.getPhoneNumber());
        wrapper.eq(userDto.getStatus()!=null,User::getStatus, userDto.getStatus());
        Map<String, Object> params = userDto.getParams();
        if (params != null) {
            String beginTimeStr = (String) params.get("beginTime");
            String endTimeStr = (String) params.get("endTime");
            //将字符串解析成时间
            LocalDateTime beginTime = LocalDateTimeUtil.parse(beginTimeStr);
            LocalDateTime endTime = LocalDateTimeUtil.parse(endTimeStr);
            if (beginTime!=null && endTime!=null) {
                wrapper.between(User::getCreateTime, beginTime, endTime);
            }
        }
        userMapper.selectPage(page, wrapper);
        return new PageResult(page.getTotal(), page.getRecords());
    }

    @Override
    public void addUser(UserDto userDto) {
        User user = new User();
        BeanUtils.copyProperties(userDto,user);
        //统计商机数，线索数
        userMapper.insert(user);
    }

    @Override
    public List<User> selectByDeptId(Long deptId) {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(deptId!=null,User::getDeptId,deptId);
        List<User> users = userMapper.selectList(wrapper);
        return users;
    }
}
